package com.ruangong.GitClient.app.TravelExpense;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.ruangong.GitClient.R;

import java.util.List;

public class TravelEventDetailsActivity extends AppCompatActivity {
    private TravelEvent travelEvent;
    private List<Expense> expenses;
    private ListView listViewExpenses;
    private ArrayAdapter<Expense> adapter;
    private TravelDBHelper dbHelper;

    // 添加请求码常量
    private static final int ADD_EXPENSE_REQUEST = 1;

    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traveleventdetails);

        // Initialize views
        listViewExpenses = findViewById(R.id.listViewExpenses);
        FloatingActionButton buttonAddExpense = findViewById(R.id.buttonAddExpense);
        ImageButton buttonShowTotalExpense = findViewById(R.id.buttonShowTotalExpense);

        // Initialize DatabaseHelper
        dbHelper = new TravelDBHelper(this);

        // Get TravelEvent data from intent
        travelEvent = (TravelEvent) getIntent().getSerializableExtra("TRAVEL_EVENT");


        // Perform null check for travelEvent
        if (travelEvent == null) {
            Toast.makeText(this, "Travel event is null", Toast.LENGTH_SHORT).show();
            // Finish the activity if travelEvent is null
            finish();
            return;
        }

        // Assuming you have TextViews in your layout to show the event name and number of people
        TextView textViewEventName = findViewById(R.id.textViewEventName);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) TextView textViewNumberOfPeopleTitle = findViewById(R.id.textViewTitle); // 新增的标题 TextView
        TextView textViewNumberOfPeople = findViewById(R.id.textViewNumberOfPeople);

        textViewEventName.setText(travelEvent.getName());
        textViewNumberOfPeopleTitle.setText("人数: "); // 设置标题为“人数”
        textViewNumberOfPeople.setText(String.valueOf(travelEvent.getNumberOfPeople()));


        // Get list of expenses associated with this travel event
        expenses = dbHelper.getExpensesForEvent(travelEvent.getId());

        // Set up ListView adapter
        adapter = new ExpensesListAdapter(this, expenses);
        listViewExpenses.setAdapter(adapter);


        // 设置按钮点击监听器
        buttonAddExpense.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在此处启动 AddExpenseActivity，并使用 startActivityForResult()
                startActivityForResult(new Intent(TravelEventDetailsActivity.this, AddExpenseActivity.class), ADD_EXPENSE_REQUEST);
            }
        });

        buttonShowTotalExpense.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在此处启动一个新的 Activity 来显示总费用
                Intent intent = new Intent(TravelEventDetailsActivity.this, TotalExpenseActivity.class);
                intent.putExtra("TOTAL_EXPENSE", calculateTotalExpense());
                intent.putExtra("NUMBER_OF_PEOPLE", travelEvent.getNumberOfPeople()); // 传递人数
                startActivity(intent);
            }
        });
    }

    // Method to add expense to the database
    private void addExpenseToDatabase(final String expenseName, final double expenseAmount) {
        // Execute database operation in a background thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                // Get instance of DatabaseHelper
                TravelDBHelper dbHelper = new TravelDBHelper(TravelEventDetailsActivity.this);

                // Get eventId from the travelEvent object
                int eventId = travelEvent.getId();

                // Call the addExpense method from DatabaseHelper
                long id = dbHelper.addExpense(eventId, expenseName, expenseAmount);

                // Optionally, handle the ID returned by the addExpense method
                // For example, display a message or update UI based on the result

                // Refresh expenses list from the database
                expenses.clear();
                expenses.addAll(dbHelper.getExpensesForEvent(eventId));

                // Notify adapter that data has changed
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }


    // Override onActivityResult to handle data returned from AddExpenseActivity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ADD_EXPENSE_REQUEST && resultCode == RESULT_OK && data != null) {
            // Retrieve expense data from the returned Intent
            String expenseName = data.getStringExtra("expenseName");
            double expenseAmount = data.getDoubleExtra("expenseAmount", 0.0); // Default value 0.0

            // Call method to add expense to the database
            addExpenseToDatabase(expenseName, expenseAmount);
        }
    }

    // Method to calculate total expense
    private double calculateTotalExpense() {
        double totalExpense = 0.0;

        // Iterate through the list of expenses and sum up the amounts
        for (Expense expense : expenses) {
            totalExpense += expense.getAmount();
        }

        return totalExpense;
    }



}


